package org.bunny.vehicle.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import com.alibaba.fastjson.JSONObject;

/**
 * JSON
 * 
 * @author Bunny
 * @version 2013-6-12 下午12:00:05
 * 
 */
public class JSON {

	public static byte getByte(JSONObject obj, String key) {
		try {
			return obj.getByteValue(key);
		} catch (Exception e) {
			return 0;
		}
	}

	public static int getInteger(JSONObject obj, String key) {
		try {
			return obj.getIntValue(key);
		} catch (Exception e) {
			return 0;
		}
	}

	public static long getLong(JSONObject obj, String key) {
		try {
			return obj.getLongValue(key);
		} catch (Exception e) {
			return 0;
		}
	}

	public static String getString(JSONObject obj, String key) {
		try {
			return obj.getString(key);
		} catch (Exception e) {
			return "";
		}
	}

	public static Date getDate(JSONObject obj, String yearKey, String MonthKey, String dateKey) {
		int year = getInteger(obj, yearKey);
		int month = getInteger(obj, MonthKey) - 1;
		int date = getInteger(obj, dateKey);

		if (year < 1970 || year > 2038) {
			year = Calendar.getInstance().get(Calendar.YEAR);
		}
		if (month < 0 || month > 11) {
			month = Calendar.getInstance().get(Calendar.MONTH);
		}
		Calendar calendar = new GregorianCalendar(year, month, 1);
		if (date < 1 || date > calendar.getMaximum(Calendar.DATE)) {
			date = Calendar.getInstance().get(Calendar.DATE);
		}

		calendar.set(Calendar.DATE, date);

		return new Date(calendar.getTimeInMillis());
	}

	public static JSONObject parseObject(String json) {
		try {
			return JSONObject.parseObject(json);
		} catch (Exception e) {
			return null;
		}
	}

}
